package com.lishe.lishe.lishe.module.excitation.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerviewBaseAdapter;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.adapter.SelectedPersonAdapter;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.widget.SearchBarView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/10/31.
 * 点赞对象
 */

public class SelectPersonActivity extends BaseActivity implements View.OnClickListener {

    private TextView title;
    private Button callBack;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private SelectedPersonAdapter adapter;
    private SelectedPersonAdapter sadapter;
    private List<UserObject> users = new ArrayList<>();
    private List<UserObject> searchUsers = new ArrayList<>();
    private SearchBarView searchBarView;
    private String keyWord = "";
    private String departId;//部门ID
    private String type = "1";//类型 1：点赞 2：被赞
    private UserObject selectPerson;
    private RelativeLayout emptyLayout;
    private RelativeLayout emptyLayout2;
    private TextView emptyText;
    private String exUserId;

    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, SelectPersonActivity.class);
        activity.startActivity(intent);
    }

    public static void jump(Fragment fragment, String departId, int requscode) {
        Intent intent = new Intent(fragment.getActivity(), SelectPersonActivity.class);
        intent.putExtra("departId", departId);
        fragment.startActivityForResult(intent, requscode);
    }

    public static void jump(Activity activity, String departId, int requscode) {
        Intent intent = new Intent(activity, SelectPersonActivity.class);
        intent.putExtra("departId", departId);
        activity.startActivityForResult(intent, requscode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selected_person);
        adapter = new SelectedPersonAdapter(this,users);
        sadapter = new SelectedPersonAdapter(this, searchUsers);
        departId = getIntent().getStringExtra("departId");
        exUserId = SharedPreferencesUtils.getExcitationUserId(SelectPersonActivity.this);
        initView();
    }

    private void initView() {
        title = findViewById(R.id.title_text_title);
        title.setText("点赞对象");
        emptyLayout = findViewById(R.id.empty_layout1);
        emptyLayout2 = findViewById(R.id.empty_layout2);
        emptyText = findViewById(R.id.tip_text);
        callBack = findViewById(R.id.title_left_button);
        recyclerView = findViewById(R.id.recyclerView);
        refreshLayout = findViewById(R.id.refreshlayout);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        searchBarView = findViewById(R.id.searBarView);
        setListener();
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        searchBarView.setOnSearchClicListener(new SearchBarView.Onclick() {
            @Override
            public void onSearchClick(EditText ed, String text) {
                keyWord = text;
                searchUsers.clear();
                recyclerView.setAdapter(sadapter);
                searchDianzanPerson();
            }

            @Override
            public void onCanclClick() {
                recyclerView.setAdapter(adapter);
                keyWord = "";
            }
        });
//        recyclerView.setOnRefreshListener(new RecyclerViewRefreshListener() {
//            @Override
//            public void onHeaderRefresh(View headerView) {
//                getDianzanPerson();
//                if (TextUtils.isEmpty(keyWord)) {
//                    users.clear();
//                    adapterNotify();
//                    getDianzanPerson();
//                } else {
//                    searchUsers.clear();
//                    adapterNotify();
//                    searchDianzanPerson();
//                }
//            }
//
//            @Override
//            public void onFooterRefresh(View footerViwe) {
//                recyclerView.setFooterRefreshEnabled(false);
//            }
//        });
//        recyclerView.setOnItemClickListener(new RefreshRecyclerView.ItemClickListener() {
//            @Override
//            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
//                if (TextUtils.isEmpty(keyWord)) {
//                    selectPerson = users.get(position);
//                    if(exUserId.equals(selectPerson.getUserId())){
//                        toast("不能点赞自己！");
//                        return;
//                    }
//                    finishThis();
//                } else {//搜索后选择用户
//                    selectPerson = searchUsers.get(position);
//                    if(exUserId.equals(selectPerson.getUserId())){
//                        toast("不能点赞自己！");
//                        return;
//                    }
//                    finishThis();
//                }
//            }
//        });
//        recyclerView.setRefreshing();
        refreshLayout.setEnableLoadmore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getDianzanPerson();
                if (TextUtils.isEmpty(keyWord)) {
                    users.clear();
                    adapterNotify();
                    getDianzanPerson();
                } else {
                    searchUsers.clear();
                    adapterNotify();
                    searchDianzanPerson();
                }
            }
        });
        adapter.setOnItemClickListener(new RecyclerviewBaseAdapter.ItemListener.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                if (TextUtils.isEmpty(keyWord)) {
                    selectPerson = users.get(position);
                    if (exUserId.equals(selectPerson.getUserId())) {
                        toast("不能点赞自己！");
                        return;
                    }
                    finishThis();
                } else {//搜索后选择用户
                    selectPerson = searchUsers.get(position);
                    if (exUserId.equals(selectPerson.getUserId())) {
                        toast("不能点赞自己！");
                        return;
                    }
                    finishThis();
                }
            }
        });
        refreshLayout.autoRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }

    private void searchDianzanPerson() {
        HttpExcitation.searchDianZanPerson(Globals.getToken(), keyWord, searchResponseHandler);
    }

    AsyncHttpResponseHandler searchResponseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            refreshLayout.finishRefresh();
            String result = new String(responseBody);
            Log.e("搜索点赞对象", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    searchUsers.clear();
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONObject info = infoArray.optJSONObject(i);
                        UserObject userObject = new UserObject();
                        userObject.setComId(info.optString("comId"));
                        userObject.setEmpName(info.optString("userName"));
                        userObject.setUserId(info.optString("userId"));
                        userObject.setAvatarPath(info.optString("avatarPath"));
                        searchUsers.add(userObject);
                    }
                    if (searchUsers.size() == 0) {
                        emptyLayout2.setVisibility(View.VISIBLE);
                        emptyLayout.setVisibility(View.GONE);
                        emptyText.setText("没有找到该用户！");
                    } else {
                        emptyLayout.setVisibility(View.GONE);
                    }
                    adapterNotify();
                } else {
                    toast(json.optString("msg"));
                    emptyLayout2.setVisibility(View.VISIBLE);
                    emptyLayout.setVisibility(View.GONE);
                    emptyText.setText("加载失败！");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                emptyLayout2.setVisibility(View.VISIBLE);
                emptyLayout.setVisibility(View.GONE);
                emptyText.setText("加载失败！");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            refreshLayout.finishRefresh();
            emptyLayout2.setVisibility(View.VISIBLE);
            emptyLayout.setVisibility(View.GONE);
            emptyText.setText("加载失败！");
        }
    };

    /**
     * 获取部门下的成员列表
     */
    private void getDianzanPerson() {
        HttpExcitation.searchOrganization(Globals.getToken(), departId, getResponseHandler);
    }

    AsyncHttpResponseHandler getResponseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            refreshLayout.finishRefresh();
            String result = new String(responseBody);
            Log.e("获取点赞对象", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject data = json.optJSONObject("data");
                    JSONArray infoArray = data.optJSONArray("info");
                    for (int i = 0; i < infoArray.length(); i++) {
                        JSONArray infoArray0 = infoArray.optJSONArray(i);
                        if (i == 0) {
//                            for (int j = 0; j < infoArray0.length(); j++) {
//                                JSONObject info = infoArray0.optJSONObject(j);
//                                DivisionObject divisionObject = new DivisionObject();
//                                divisionObject.setComId(info.optString("comId"));
//                                divisionObject.setDeptId(info.optString("deptId"));
//                                divisionObject.setDeptName(info.optString("deptName"));
//                            }
                        } else if (i == 1) {
                            users.clear();
                            for (int j = 0; j < infoArray0.length(); j++) {
                                JSONObject info = infoArray0.optJSONObject(j);
                                UserObject userObject = new UserObject();
                                userObject.setComId(info.optString("comId"));
                                userObject.setEmpName(info.optString("empName"));
                                userObject.setUserId(info.optString("userId"));
                                userObject.setAvatarPath(info.optString("avatarPath"));
                                users.add(userObject);
                            }
                            if (users.size() > 0) {
                                emptyLayout.setVisibility(View.GONE);

                            } else {
                                emptyLayout2.setVisibility(View.GONE);
                                emptyLayout.setVisibility(View.VISIBLE);
                                emptyText.setText("没有成员");
                            }
                        }
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    toast(json.optString("msg"));
                    emptyLayout2.setVisibility(View.GONE);
                    emptyLayout.setVisibility(View.VISIBLE);
                    emptyText.setText("加载失败！");
                }
            } catch (JSONException e) {
                e.printStackTrace();
                emptyLayout2.setVisibility(View.GONE);
                emptyLayout.setVisibility(View.VISIBLE);
                emptyText.setText("加载失败！");
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            refreshLayout.finishRefresh();
            emptyLayout2.setVisibility(View.GONE);
            emptyLayout.setVisibility(View.VISIBLE);
            emptyText.setText("加载失败！");
        }
    };

    private void finishThis() {
        Intent intent = new Intent();
        intent.putExtra("diazanPerson", selectPerson);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void adapterNotify() {
        if (TextUtils.isEmpty(keyWord)) {
            adapter.notifyDataSetChanged();
        } else {
            sadapter.notifyDataSetChanged();
        }
    }
}
